import multiprocessing
import os

from sentinelsat import SentinelAPI

accounts = [
    ["fyy001", "show1234"],
    ["fyy_01", "show1234"],
    ["fyy_02", "show1234"],
    ["fyy_03", "show1234"],
    ["fyy_04", "show1234"],
    ["hxx2021", "hxx2021123"],
    ["hxx2022", "hxx2022123"],
    ["hxx20221", "hxx2022123"],
    ["hxx20222", "hxx20222123"]]

def downloader(args):
    queue,productids,savefolder=args
    key = queue.get(block=True)
    username,password = accounts[key]
    api=SentinelAPI(
        username,
        password,
        'https://scihub.copernicus.eu/dhus/',
        show_progressbars=True,timeout=60)
    
    r = api.download_all(
        productids,
        directory_path=savefolder,
        max_attempts=2,  # 尝试下载次数
        checksum=True,
        n_concurrent_dl=4)  # 单个账号只允许最多四个并发流	
    queue.put(key,block=True)
    return

def main(filefolder,savefolder):
    productids = []
    for txtname in os.listdir(filefolder): 
        txtpath = os.path.join(filefolder,txtname)
        with open(txtpath,'r') as file:
            for row in file.readlines():
                tmp_list = row.split(' ')
                if "Download" not in tmp_list:continue
                productid = tmp_list[-1].replace('\n','').split("'")[1]
                productids.append(productid) #将每行数据插入data中
    productids = list(tuple(productids))
    manager = multiprocessing.Manager()
    queue = manager.Queue()
    for i in range(len(accounts)):queue.put(i)
    productidgroups = [productids[i:i+4] for i in range(0,len(productids),4)]  # 分组
    argsList = [[queue,productidgroup,savefolder] for productidgroup in productidgroups]
    pool = multiprocessing.Pool(10)
    pool.map(downloader,argsList)
    pool.close()
    pool.join()
    return

if __name__ == "__main__":
    # os.system("net use Z: \\192.168.2.172\root DELL123dell /user:root ")
    # filefolder = r"E:\Image2\txt" 
    # savefolder = r"E:\Image2\zip"
    # print(os.path.exists(savefolder))
    main(filefolder,savefolder)
